package com.eco.fanliapp.admin.controller.web;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eco.fanliapp.admin.annotation.SysLogAnnotation;
import com.eco.fanliapp.admin.common.BaseController;
import com.eco.fanliapp.common.response.ServerResponse;
import com.eco.fanliapp.entity.AppCompany;
import com.eco.fanliapp.entity.SyChannel;
import com.eco.fanliapp.entity.SyTimePeriod;
import com.eco.fanliapp.entity.SysLog;
import com.eco.fanliapp.service.IAppCompanyService;
import com.eco.fanliapp.service.ISyChannelService;
import com.eco.fanliapp.service.RedisTemplateService;
import com.eco.fanliapp.service.SysLogCommon;
import com.eco.fanliapp.service.impl.SyChannelServiceImpl;
import com.eco.fanliapp.utils.*;
import com.eco.fanliapp.vo.SyChannelGroupVo;
import com.eco.fanliapp.vo.SyChannelUserVO;
import com.eco.fanliapp.vo.SyChannelVo;
import com.eco.fanliapp.vo.UserVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 渠道表 前端控制器
 * </p>
 *
 * @author jobob
 * @since 2019-08-21
 */
@RestController
@RequestMapping("/web/channel")
public class SyChannelController extends BaseController {

    @Autowired
    private ISyChannelService syChannelService;
    @Autowired
    private RedisTemplateService redisTemplateService;
    @Autowired
    private SysLogCommon sysLogCommon;

    @GetMapping("/handleDate")
    public ServerResponse handleDate(Integer companyId){
        syChannelService.handleDate(companyId);
        return ServerResponse.createBySuccessMessage("获取成功");

    }
    @GetMapping("/handleNotChannel")
    public ServerResponse handleNotChannel(Integer companyId){
        syChannelService.handleNotChannel(companyId);
        return ServerResponse.createBySuccessMessage("获取成功");

    }
    /**
     * 列表（分页）
     *
     * @return
     */
    @GetMapping(value = "syChannelList")
    public ServerResponse syChannelList(@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "20") Integer pageSize,String keyWord,Integer groupId) {
        Integer companyId = getAuthentication().getCompanyId();

        PageHelper.startPage(pageNum, pageSize);
        QueryWrapper queryWrapper = new QueryWrapper();
        if (companyId != 1) {
            queryWrapper.eq("company_id", companyId);
        }
        queryWrapper.eq("enable", 1);
        queryWrapper.eq("deleted", 0);
        if(StringUtils.isNotNull(keyWord)){
            queryWrapper.like("channel_name",keyWord);
        }
        if(groupId != null){
            queryWrapper.eq("group_id", groupId);
        }
        List<SyChannel> list = syChannelService.list(queryWrapper);

        return ServerResponse.createBySuccess("查询成功", new PageInfo(list));
    }

    /**
     * 新列表(不分页)
     *
     * @return
     */
    @GetMapping(value = "syChannelListNew")
    public ServerResponse syChannelListNew() {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("enable", 1);
        queryWrapper.eq("deleted", 0);
        List list = syChannelService.list(queryWrapper);
        return ServerResponse.createBySuccess("查询成功", list);
    }

    /**
     * 新增渠道接口
     *
     * @param syChannel
     * @return
     */
    @PostMapping(value = "syChannelSave")
    public ServerResponse syChannelSave(@RequestBody SyChannel syChannel) {
        //校验参数不能为空
        Integer companyId = syChannel.getCompanyId();
        String channelName = syChannel.getChannelName();
        Integer groupId = syChannel.getGroupId();
        UserVO authentication1 = getAuthentication();
        if (companyId == null) {
            syChannel.setCompanyId(authentication1.getCompanyId());
        }
        if (channelName == null || "".equals(channelName)) {
            return ServerResponse.createByErrorMessage("参数channelName不能为空");
        }
        if(groupId ==null){
            return ServerResponse.createByErrorMessage("参数groupId不能为空");
        }
        //校验渠道不允许为重复
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("company_id", syChannel.getCompanyId());
        queryWrapper.eq("channel_name", syChannel.getChannelName());
        queryWrapper.eq("enable", 1);
        queryWrapper.eq("deleted", 0);
        //校验同公司下渠道名称是否重复
        int count = syChannelService.count(queryWrapper);
        if (count > 0) {
            return ServerResponse.createByErrorMessage("渠道名称重复");
        }

        //生成邀请码
        String inviteCode = UUIDUtils.generateShortUuid();
        syChannel.setChannelInviteCode(inviteCode);
        //生成短链
        String shortUrl = syChannelService.linkCreateNew(inviteCode, syChannel.getCompanyId());
        syChannel.setChannelLink(shortUrl);
        syChannel.setGroupId(groupId);
        syChannelService.save(syChannel);
		//删除渠道统计列表缓存
        String redisKey = "manageStatisticalNew_" + DateFormatUtils.getNowDateDay(new Date()) + "_" + companyId;
        if(redisTemplateService.hasKey(redisKey)){
            redisTemplateService.del(redisKey);
        }
        SysLog sysLog = new SysLog();
        UserVO authentication = getAuthentication();
        sysLog.setUserId(authentication.getUserId());
        sysLog.setMethodExplain("新增了渠道--"+syChannel.getChannelName());
        sysLog.setResponseParams("成功");
        sysLogCommon.save(sysLog);
        return ServerResponse.createBySuccess("操作成功");

    }
	/**
	 * 删除/修改渠道
	 *
	 * @param syChannel
	 * @return
	 */
	@PostMapping(value = "syChannelDel")
	public ServerResponse syChannelDel(@RequestBody SyChannel syChannel) {
        Integer groupId = syChannel.getGroupId();
		//校验参数不能为空
		Long tableId = syChannel.getTableId();
		if (tableId == null) {
			return ServerResponse.createByErrorMessage("渠道tableId不能空！");
		}
        if(groupId ==null){
            return ServerResponse.createByErrorMessage("参数groupId不能为空");
        }
		//修改
		SyChannel syChannelNew = syChannelService.getByTableId(syChannel.getTableId());
		if (syChannelNew == null) {
			return ServerResponse.createByErrorMessage("该渠道id不存在！");
		}
		if(syChannel.getDeleted() !=null){
            syChannelNew.setDeleted(true);
        }
        syChannelNew.setGroupId(groupId);
		syChannelService.updateById(syChannelNew);
        SysLog sysLog = new SysLog();
        UserVO authentication = getAuthentication();
        sysLog.setUserId(authentication.getUserId());
        sysLog.setMethodExplain("修改了渠道--"+syChannel.getChannelName());
        sysLog.setResponseParams("成功");
        sysLogCommon.save(sysLog);
		return ServerResponse.createBySuccess("操作成功");
	}

    /**
     * 刷新渠道短链
     *
     * @param syChannel
     * @return
     */
    @PostMapping(value = "syChannelUpdate")
    @SysLogAnnotation(value = "刷新了渠道短链",userType = 2)
    public ServerResponse syChannelUpdate(@RequestBody SyChannel syChannel) {
        Long tableId = syChannel.getTableId();
        if(tableId == null){
            return ServerResponse.createByErrorMessage("渠道id不能为空！");
        }
        SyChannel syChannelNew = syChannelService.getByTableId(syChannel.getTableId());
        //生成短链
        String shortUrl = syChannelService.linkCreateNew(syChannelNew.getChannelInviteCode(), syChannel.getCompanyId());
        syChannelNew.setChannelLink(shortUrl);
        syChannelService.updateById(syChannelNew);
        return ServerResponse.createBySuccess("操作成功");
    }

	/**
	 * 批量刷新短链
	 * @return
	 */
    @PostMapping(value = "syChannelUpdateBath")
    @SysLogAnnotation(value = "批量刷新了渠道短链",userType = 2)
    public ServerResponse syChannelUpdateBath() {
        //校验渠道不允许为重复
        QueryWrapper<SyChannel> queryWrapper = new QueryWrapper();
        queryWrapper.eq("enable", 1);
        queryWrapper.eq("deleted", 0);
        List<SyChannel> list = syChannelService.list(queryWrapper);
        if(!CollectionUtils.isEmpty(list)){
            List<SyChannel> listNew = new ArrayList<>();
            for(SyChannel channel:list){
                //生成短链
                String shortUrl = syChannelService.linkCreateNew(channel.getChannelInviteCode(), channel.getCompanyId());
                //创建新的对象，批量更新用
                SyChannel syChannelNew = new SyChannel();
                syChannelNew.setTableId(channel.getTableId());
                syChannelNew.setChannelLink(shortUrl);
                listNew.add(syChannelNew);
            }
            syChannelService.updateBatchById(listNew);
        }
        return ServerResponse.createBySuccess("操作成功");
    }



    /**
     * 渠道列表
     * @param companyId
     * @param searchDate
     * @return
     */
    @RequestMapping("/manage/statisticalNew")
    public ServerResponse manageStatisticalNew(Integer companyId, String searchDate) {
        if(companyId == null){
            UserVO userVO = getAuthentication();
            if (userVO.getCompanyId() != 1) {
                companyId = userVO.getCompanyId();
            }
        }

        List<SyChannelUserVO> list = syChannelService.manageStatisticalNew(companyId, searchDate);
        return ServerResponse.createBySuccess(list);
    }

    /**
     * 统计记录导出
     *
     * @param response
     */
    @RequestMapping("/exportNew")
    @SysLogAnnotation(value = "导出了渠道列表",userType = 2)
    public void exportManageStatisticalNew(HttpServletResponse response, Integer companyId, String searchDate) {
        if(companyId == null){
            UserVO userVO = getAuthentication();
            if (userVO.getCompanyId() != 1) {
                companyId = userVO.getCompanyId();
            }
        }
        List<SyChannelUserVO> excel = syChannelService.manageStatisticalNew(companyId, searchDate);
        EasyPoiUtils.exportExcel(excel, "渠道关系统计", "渠道关系统计", SyChannelUserVO.class, EasyPoiStyleUtils.class, "渠道关系统计.xls", response);

    }
    /**
     * 渠道统计下详情
     *
     * @param channelId
     * @return
     */
    @RequestMapping("/statistical/detailNew")
    public ServerResponse statisticalDetailNew(Long channelId) {

        List<SyChannelUserVO> list = syChannelService.statisticalDetailNew(channelId);
        return ServerResponse.createBySuccess(list);
    }
    /**
     * 渠道统计下详情缓存清除
     *
     * @param channelId
     * @return
     */
    @RequestMapping("/statistical/clearDate")
    public ServerResponse clearDate(Long channelId) {

       syChannelService.clearDate(channelId);
        return ServerResponse.createBySuccessMessage("渠道缓存清除完毕");
    }

    /**
     * 渠道统计下详情导出
     *
     * @param channelId
     * @return
     */
    @RequestMapping("/detail/exportNew")
    @SysLogAnnotation(value = "导出了渠道详情统计")
    public void exporttatisticalDetailNew(HttpServletResponse response, Long channelId) {

        List<SyChannelUserVO> list = syChannelService.statisticalDetailNew(channelId);
        //导出excel
        EasyPoiUtils.exportExcel(list, "渠道详情统计", "渠道详情统计", SyChannelUserVO.class, EasyPoiStyleUtils.class, "渠道详情统计.xls", response);
    }

//    ====================旧版本===================
    /**
     * 统计渠道（注册量、下单量）（支持到4.4.2）
     *
     * @param companyId
     * @param searchDate
     * @return
     */
    @RequestMapping("/manage/statistical")
    public ServerResponse manageStatistical(@RequestParam(defaultValue = "1") int currentPage, @RequestParam(defaultValue = "10") int pageSize,Integer companyId, String searchDate,String keyWord) {
        UserVO userVO = getAuthentication();
        if (userVO.getCompanyId() != 1) {
            companyId = userVO.getCompanyId();
        }
        return syChannelService.manageStatistical(currentPage,pageSize,companyId, searchDate,keyWord);
    }
    /**
     * 统计记录导出（支持到4.4.2）
     *
     * @param response
     */
    @RequestMapping("/export")
    @SysLogAnnotation(value = "导出了统计记录导出")
    public void exportManageStatistical(HttpServletResponse response, Integer companyId, String searchDate) {
        UserVO userVO = getAuthentication();
        if (userVO.getCompanyId() != 1) {
            companyId = userVO.getCompanyId();
        }
        syChannelService.exportManageStatistical(response, companyId, searchDate);
    }


    /**
     * 渠道统计下详情（支持到4.4.2）
     *
     * @param channelId
     * @return
     */
    @RequestMapping("/statistical/detail")
    public ServerResponse statisticalDetail(@RequestParam(defaultValue = "1") int currentPage, @RequestParam(defaultValue = "10") int pageSize, Long channelId) {

        return syChannelService.statisticalDetail(currentPage, pageSize, channelId);
    }
    /**
     * 渠道统计下详情导出（支持到4.4.2）
     *
     * @param channelId
     * @return
     */
    @RequestMapping("/detail/export")
    @SysLogAnnotation(value = "渠道统计下详情导出")
    public void exporttatisticalDetail(HttpServletResponse response, Long channelId) {

        syChannelService.exporttatisticalDetail(response, channelId);
    }

    //========================渠道组统计=================
    /**
     * 渠道组下6大数据类型统计（实时查询）
     *     type = 1 转口令渠道 1，2，3，4
     *     type = 2 瀑布渠道  15
     *     type = 3 搜索渠道  18， 19
     *     type = 4 淘礼金渠道 24
     *     type = 5 社群后返渠道  26
     *     type= 6 各商城点击渠道  未知
     * @param groupId
     * @param startTime
     * @param endTime
     * @return
     */
    @RequestMapping("/groupList")
    public ServerResponse groupListStatic(Integer groupId,Long startTime,Long endTime) {
        //获取指定渠道组下所有渠道
        List<Integer> channelList = syChannelService.findChannelListByGroupId(groupId);
//        if(CollectionUtils.isEmpty(channelList)){
//            return ServerResponse.createBySuccess("该组下暂无渠道！",new ArrayList());
//        }

        //各渠道组数据
        List<SyChannelGroupVo> list = syChannelService.groupList(channelList, startTime, endTime);
        return ServerResponse.createBySuccess("接口请求成功",list);
    }

    /**
     * 查询某个渠道组下每个渠道下的具体数据
     * @param groupId
     * @param startTime
     * @param endTime
     * @return
     */
    @RequestMapping("/channelDetailList")
    public ServerResponse channelDetailList(Integer groupId,Long startTime,Long endTime,String channelName) {
        if(groupId == null){
            return ServerResponse.createBySuccess("渠道组id必传！",new ArrayList<>());
        }

        //各渠道下数据统计
        List<SyChannelGroupVo> list = syChannelService.channelDetailList(groupId, startTime, endTime,channelName);
        return ServerResponse.createBySuccess("接口请求成功",list);
    }

}
